package com.blb.seckill.controller;

import com.blb.seckill.entity.SeckillOrder;
import com.blb.seckill.service.SeckillOrderService;
import com.blb.seckill.util.TokenDecoder;
import com.learn.eduapi.util.CookieUtil;
import com.learn.eduapi.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 秒杀订单控制器
 */
@RestController
public class SeckillOrderController {

    @Autowired
    private TokenDecoder tokenDecoder;

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 当前登录用户对某个时间段的某个课程下单
     * @param id
     * @return
     */
    @RequestMapping("/seckill/order")
    public ResponseEntity<String> addOrder(Long id,String random){
        //校验密文有效
        String randomcode = (String) redisTemplate.boundValueOps("randomcode_" + readCookie()).get();
        if (StringUtils.isEmpty(randomcode) || !random.equals(randomcode)){
            return ResponseEntity.ok("访问失败");
        }
        //从token中获得用户信息
        String username = tokenDecoder.getUserInfo().get("username");
        //下单
        SeckillOrder order = seckillOrderService.addOrder(id, username);
        if(order == null) {
            return ResponseEntity.ok("下单失败");
        }
        return ResponseEntity.ok("下单成功");
    }

    @Autowired
    private RedisTemplate redisTemplate;

    ////秒杀下单
    @GetMapping("/seckill/getToken")
    @ResponseBody
    public String getToken(){
        String randomString = RandomUtil.getRandomString();
        String cookieValue = this.readCookie();
        redisTemplate.opsForValue().set("randomcode_"+cookieValue,randomString,5, TimeUnit.SECONDS);
        return randomString;
    }

    private String readCookie(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String jti = CookieUtil.readCookie(request, "uid").get("uid");
        return jti;
    }
}
